using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectTrojan : MonoBehaviour
{
    public float detectionRange = 10.0f; // 检测范围
    public string targetTag = "Enemy"; // 目标标签

    public int level = 1; // 检测塔等级
    public int maxHealth = 100; // 最大生命值
    public int health = 100; // 当前生命值
    public int attackPower = 20; // 攻击力
    public float attackSpeed = 1.0f; // 攻击速度（每秒攻击次数）
    public int maxTargets = 1; // 最大同时攻击目标数

    private float attackTimer = 0f; // 攻击计时器
    private List<GameObject> targets = new List<GameObject>(); // 存储检测到的目标

    void Update()
    {
        // 检测范围内的所有碰撞体
        Collider[] colliders = Physics.OverlapSphere(transform.position, detectionRange);

        // 遍历检测到的碰撞体
        foreach (Collider collider in colliders)
        {
            // 检查碰撞体是否具有指定的标签
            if (collider.CompareTag(targetTag) && !targets.Contains(collider.gameObject))
            {
                targets.Add(collider.gameObject);
            }
        }

        // 移除超出范围的目标
        for (int i = targets.Count - 1; i >= 0; i--)
        {
            if (targets[i] == null || Vector3.Distance(transform.position, targets[i].transform.position) > detectionRange)
            {
                targets.RemoveAt(i);
            }
        }

        // 攻击检测到的目标
        attackTimer += Time.deltaTime;
        if (attackTimer >= 1.0f / attackSpeed)
        {
            for (int i = 0; i < targets.Count && i < maxTargets; i++)
            {
                if (targets[i] != null)
                {
                    Trojan tro = targets[i].GetComponent<Trojan>();
                    if (tro != null)
                    {
                        tro.TakeDamage(attackPower);
                    }
                }
            }
            attackTimer = 0f;
        }
    }

    void OnDrawGizmosSelected()
    {
        // 绘制检测范围的可视化
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere(transform.position, detectionRange);
    }

    // 升级检测塔
    public void Upgrade()
    {
        level++;
        health = maxHealth; // 恢复满血
        attackPower += 5; // 提升攻击力
        attackSpeed -= 0.1f; // 提升攻击速度
        detectionRange += 2.0f; // 增加索敌范围
        maxTargets++; // 增加同时可攻击敌人数量
    }
}
